<?php

class ShellLauncher
{

    private $pid;
    private $command;
    private $out;
	
	private $process_launch_wait;
	private $process_checkstatus_interval;

	// main
    public function __construct($command='',$out='/dev/null',$process_launch_wait=1,$process_checkstatus_interval=1)
	{
		$this->out=$out;
		$this->command = $command;
		$this->process_launch_wait=$process_launch_wait;
		$this->process_checkstatus_interval=$process_checkstatus_interval;
    }
	
	public function run($timeout=5)
	{
		$this->runCom();
		usleep($this->process_launch_wait*1000000); // wait for launch process
		
		$c=0;
		while($this->status()){
			if($c>=$timeout){
				$this->kill();
				break;
			}
			$c++;
			usleep($this->process_checkstatus_interval*1000000);
		}
		return $c!=$timeout;
	}
	
	//utility
	public function checkDirAccess($dir,$timeout=5)
	{
		$this->command="ls $dir";
		$c=$this->run($timeout);
		return !$c? 0 : (is_dir($dir) ? 1 : 0);
	}
	
	// basic
    private function runCom()
	{
        $command = 'nohup '.$this->command." > {$this->out} 2>&1 & echo $!";
        exec($command ,$op);
        $this->pid = (int)$op[0];
    }

    public function status()
	{
        $command = 'ps -p '.$this->pid;
        exec($command,$op);
        if (!isset($op[1]))return false;
        else return true;
    }

    public function kill()
	{
        $command = 'kill '.$this->pid;
        exec($command);
        if ($this->status() == false)return true;
        else return false;
    }
}